<template>
	<view class="login margin-top">
		<div class="logo mb20">
			<image src="../../static/logo.png" mode="widthFix"></image>
			<view class="text-theme">我滴记账本</view>
		</div>
		<u--form labelPosition="left" ref="uForm">
			<u-form-item>
				<u--input placeholder="请输入手机号码" prefixIcon="phone" border="surround" v-model="phone" type="number"
					:maxlength="11"></u--input>

			</u-form-item>

			<u-form-item>
				<u--input placeholder="请输入登录密码" prefixIcon="lock" border="surround" v-model="password"
					type="password"></u--input>
			</u-form-item>

			<u-form-item>
				<button class="btn-theme" @tap="login()">登录</button>

			</u-form-item>

			<div class="mt20">
				<u-button type="success" text="微信登录" @tap="wxLogin()"></u-button>
			</div>
			
			

		</u--form>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex';
	import UserModel from '@/models/UserModel'

	export default {
		data() {
			return {
				phone: '',
				password: ''
			}
		},
		onLoad() {
		},
		methods: {
			...mapMutations(['changeUserInfo']),
			login() {
				var preg = /^1\d{10}$/;
				if (!preg.test(this.phone)) {
					this.$base.msg('手机号码格式不正确');
					return false;
				}

				if (!this.password) {
					this.$base.msg('密码不能为空');
					return false;
				}

				uni.showLoading({
					mask: true
				})

				UserModel.login(this.phone,this.password).then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						this.changeUserInfo(res.data.userinfo);
						this.$base.msg('登录成功')
						uni.reLaunch({
							url: '/pages/index/index'
						})
					} else {
						this.$base.alert(res.msg)
					}
				})
			},
			wxLogin() {
				let that = this
				uni.showLoading({
					mask: true
				})
				uni.login({
					provider: 'weixin',
					success(res) {
						console.log('res', res)
						try{
				
						UserModel.wxLogin(res.code).then(result => {
							uni.hideLoading()
							if (result.code == 200) {
								that.changeUserInfo(result.data);
								that.$base.msg('登录成功')
								uni.reLaunch({
									url: '/pages/index/index'
								})
							} else {
								that.$base.alert(result.msg)
							}
						})
						
						}catch(e){
							//TODO handle the exception
							console.log('error',e)
						}
					}
				})
			}

		}
	}
</script>

<style scoped lang="scss">
	.login {
		padding: 80upx;

		.logo {
			text-align: center;

			image {
				width: 120rpx;
				height: 120rpx;
			}
		}
	}
</style>